﻿//----------------------------------------------------------------
//CodeArt.
//
//文件描述:
//
//创 建 人: dreamnan@hotmail.com(Blog:http://www.cnblogs.com/dreamnan)
//创建日期: 2010-6-15
//
//修订记录: 
//
//----------------------------------------------------------------

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System;
using System.ComponentModel;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using System.Collections.Generic;
using WebPart = System.Web.UI.WebControls.WebParts.WebPart;
using System.Web.UI.WebControls.WebParts;

namespace CodeArt.SharePoint.SmartQuery
{
    internal class ListQueryToolPart : EditorPart
    {
        #region Variable

        private Label lblColumnsNum;
        private SPList _currentList = null;
        
        private Table tblContent;
        private FieldCheckBoxGroup tblFieldCheck = null;

        private TextBox txtColumnsNum;
        private RangeValidator valColumnsNum;
        private RequiredFieldValidator valColumnsNumReq;
        private ListQueryWebPart webPart;

        #endregion

        #region Construct
        /// <summary>
        /// 根据配置信息构造
        /// </summary>
        /// <param name="config"></param>
        /// <param name="siteId"></param>
        public ListQueryToolPart(ListQueryWebPart listQueryPart)
        {
            this.webPart = listQueryPart;
            this._currentList = listQueryPart.List;
            
            base.Title = ResourcesHelper.GetResourceString("settingTitle", "查询条件设置") ;
        }

        #endregion

        #region Override Method
        /// <summary>
        /// Click Apply Button
        /// </summary>
        public override bool ApplyChanges()
        {
            try
            {
                this.Page.Validate();
                if (!this.Page.IsValid)
                {
                    return false;
                }
                try
                {
                    this.webPart.SuspendRedraw();
                    this.webPart.ColumnsNum = int.Parse(this.txtColumnsNum.Text);
                    this.webPart.SelectedFields = this.tblFieldCheck.GetSelectedFields();
                    this.webPart.ResumeRedraw();

                    base.ChildControlsCreated = false;
                    this.EnsureChildControls();
                    return true;
                }
                catch (Exception exception1)
                {
                    this.Controls.AddAt(0, new LiteralControl("<div class='ms-ToolPaneError'>" + exception1.Message + "</div>"));
                    throw;
                }
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 创建子控件
        /// </summary>
        protected override void CreateChildControls()
        {            
            this.Controls.Clear();
            try
            {
                this.CreateMaxColumnContent();
              
                SPList list = _currentList;
                //ListViewWebPart lvSelect = null;
                //SPView lvView = null;
                ////change by jianyi, for SP2010
                //foreach (WebPart subWebpart in WebPartManager.WebParts)
                //{
                //    if (subWebpart.GetType() == typeof(ListViewWebPart))
                //    {
                //       lvSelect = subWebpart as ListViewWebPart;
                //       lvView = list.Views[new Guid(lvSelect.ViewGuid)];
                //       break;
                //    }
                //    else if (subWebpart.GetType().Name == "XsltListViewWebPart")
                //    {
                //        var prop = subWebpart.GetType().GetProperty("ViewGuid").GetValue(subWebpart, null);
                //        lvView = list.Views[new Guid(prop.ToString())];
                //    }
                //}            
                
                //add by zjy 2011-12 计算允许查询的字段
                List<string> fields = new List<string>();
                foreach (SPField field in list.Fields)
                {
                    //if (field.Hidden) continue;
                    if (ListQueryWebPart.ExcludedFields.Contains(field.InternalName))
                        continue;
                    if (field is SPFieldWorkflowStatus)
                        continue;

                    fields.Add(field.InternalName);
                }             

                tblFieldCheck = new FieldCheckBoxGroup(fields.Count);

                string[] tags = null;
                List<string> createdFields = new List<string>();
                if (this.webPart.SelectedFields != null)//先创建选择的字段
                {
                    tags = this.webPart.SelectedFields.Split(ListQueryWebPart.s_CommaSeparator);

                    foreach (string f in tags)
                    {
                        if (!list.Fields.ContainsField(f)) continue;

                        SPField field = list.Fields.GetField(f);
                        if ((!field.Hidden))
                        {
                            tblFieldCheck.AddSeparatorItem();
                            tblFieldCheck.AddCheckField(field, true);
                            createdFields.Add(field.InternalName);
                        }
                    }
                }
                int i = tags ==null ?0 : tags.Length;
                foreach (string fieldName in fields) //然后处理未选择的字段
                {
                    SPField field = list.Fields.GetFieldByInternalName(fieldName);
                    if (!createdFields.Contains(field.InternalName))
                    {
                        if ((!field.Hidden))
                        {
                            tblFieldCheck.AddSeparatorItem();                                
                            tblFieldCheck.AddCheckField(field);
                        }
                    }
                }                                    
               
                this.Controls.Add(tblFieldCheck);

                base.ChildControlsCreated = true;
            }
            catch (Exception exception1)
            {
                this.Controls.AddAt(0, new LiteralControl("<div class='ms-toolpaneerror'>" + exception1.Message + "</div>"));
                //base.ParentToolPane.OK.Enabled = false;
                //base.ParentToolPane.Apply.Enabled = false;
            }
        }

        public override void SyncChanges()
        {
            try
            {
                this.txtColumnsNum.Text = this.webPart.ColumnsNum.ToString();
                tblFieldCheck.SetSelectedFields(this.webPart.SelectedFields);
            }
            catch (Exception exception1)
            {
                this.Controls.AddAt(0, new LiteralControl("<div class='ms-toolpaneerror'>" + exception1.Message + "</div>"));
            }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            //base.ParentToolPane.Cancel.CausesValidation = false;

            this.EnsureChildControls();
        }

        #endregion

        #region Internal Method               

        private void CreateMaxColumnContent()
        {
            this.tblContent = new Table();
            this.Controls.Add(this.tblContent);
            this.tblContent.Width = Unit.Percentage(100);

            //this.AddCell(this.tblContent, new ToolPartItemSeparator());

            this.txtColumnsNum = new TextBox();
            this.txtColumnsNum.ID = "txtColumnsNum";
            this.txtColumnsNum.Text = this.webPart.ColumnsNum.ToString();
            this.txtColumnsNum.Attributes.Add("style", "text-align:right;");
            this.txtColumnsNum.Width = Unit.Pixel(50);

            this.txtColumnsNum.ToolTip = ResourcesHelper.GetResourceString("lbColumnCountTip");

            this.lblColumnsNum = new Label();
            this.lblColumnsNum.Text = ResourcesHelper.GetResourceString("lbColumnCount", "显示列数");

            TableCell cell1 = this.AddCell(this.tblContent, this.lblColumnsNum);
            cell1.Controls.Add(this.txtColumnsNum);

            //this.valColumnsNum = new RangeValidator();
            //this.valColumnsNum.Type = ValidationDataType.Integer;
            //this.valColumnsNum.MinimumValue = "1";
            //this.valColumnsNum.MaximumValue = "6";
            //this.valColumnsNum.Text = "值必须是介于1和6之间的整数";
            //this.valColumnsNum.ControlToValidate = this.txtColumnsNum.ID;
            //this.valColumnsNum.Display = ValidatorDisplay.Dynamic;
            //this.valColumnsNum.CssClass = "ms-toolpaneerror";
            //this.valColumnsNum.Style["color"] = "";

            //cell1 = this.AddCell(this.tblContent, this.valColumnsNum);

            this.valColumnsNumReq = this.SetUpRequiredFieldValidator(this.txtColumnsNum, "*");
            cell1.Controls.Add(this.valColumnsNumReq);

            this.AddCell(this.tblContent, new ToolPartItemSeparator());
        }

        private TableCell AddCell(Table tbl, Control child)
        {
            TableRow row1 = new TableRow();
            TableCell cell1 = new TableCell();
            cell1.Controls.Add(child);
            tbl.Rows.Add(row1);
            row1.Cells.Add(cell1);
            return cell1;
        }

        //private Label GetParentPropertyValue(string propertyName)
        //{
        //    PropertyInfo info1 = base.ParentToolPane.SelectedWebPart.GetType().GetProperty(propertyName);
            
        //    Label label1 = new Label();

        //    if (info1 != null)
        //    {
        //        object[] objArray1 = info1.GetCustomAttributes(typeof(FriendlyNameAttribute), false);
        //        if (objArray1.Length > 0)
        //        {
        //            FriendlyNameAttribute attribute1 = objArray1[0] as FriendlyNameAttribute;
        //            label1.Text = attribute1.FriendlyName;
        //        }
        //        else
        //        {
        //            label1.Text = info1.Name;
        //        }
        //        objArray1 = info1.GetCustomAttributes(typeof(DescriptionAttribute), false);
        //        if (objArray1.Length > 0)
        //        {
        //            DescriptionAttribute attribute2 = objArray1[0] as DescriptionAttribute;
        //            label1.ToolTip = attribute2.Description;
        //        }              
        //    }
        //    return label1;
        //}

        private RequiredFieldValidator SetUpRequiredFieldValidator(Control c, string text)
        {
            RequiredFieldValidator validator1 = new RequiredFieldValidator();
            validator1.ControlToValidate = c.ID;
            validator1.EnableClientScript = true;
            validator1.Display = ValidatorDisplay.Dynamic;
            validator1.CssClass = "ms-toolpaneerror";
            validator1.Style["color"] = "";
            validator1.Text = text;
            return validator1;
        }
        
        private SPWeb Web
        {
            get { return _currentList.ParentWeb; }
        }

        private new SPSite Site
        {
            get { return this._currentList.ParentWeb.Site; }
        }
        #endregion
    }       

    internal class OrderByComparer : IComparer<SelectedField>
    {
        //实现Index升序
        public int Compare(SelectedField x, SelectedField y)
        {
            return (x.Index.CompareTo(y.Index));
        }
    }

    internal struct SelectedField
    {
        public string FieldName { get; set; }
        public int Index { get; set; }
    }

    internal class ToolPartItemSeparator : WebControl
    {
        protected override void Render(HtmlTextWriter output)
        {
            output.Write("<div style='width:100%' class='UserDottedLine'></div>");
        }
    }

    internal class HeaderTextControl : LiteralControl
    {
        public HeaderTextControl(string text)
            : base(text)
        { }
        protected override void Render(HtmlTextWriter output)
        {
            output.Write(string.Format("<b>{0}</b>",this.Text));
        }
    }

}
